﻿using System.Linq;
using Adalbertus.BudgetPlanner.Domain;
using Adalbertus.BudgetPlanner.Domain.Repositories;
using NHibernate.Linq;

namespace Adalbertus.BudgetPlanner.Infrastructure.Repositories
{
    public class ExternalSourceRepository : Repository<ExternalSource>, IExternalSourceRepository
    {
        public ExternalSourceRepository(IUnitOfWork unitOfWork)
            : base(unitOfWork)
        {
        }

        public ExternalSource GetByName(string name)
        {
            return UnitOfWork.Session.Query<ExternalSource>().FirstOrDefault(es => es.Name == name);
        }

        public override void Save(ExternalSource externalSource)
        {
            UnitOfWork.Session.SaveOrUpdate(externalSource);

            foreach (ExternalSourceItem externalSourceItem in externalSource.Items)
            {
                UnitOfWork.Session.SaveOrUpdate(externalSourceItem);
            }
        }
    }
}
